package com.hoo.auth;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hoo.auth.MyRealm.UserContext;
import com.hoo.common.constant.Constant;
import com.hoo.entity.account.Users;
import com.hoo.entity.flow.FlowUserAction;
import com.hoo.service.account.AccountService;
import com.hoo.service.flow.FlowUserActionService;
import com.hoo.util.DateUtils;
import com.hoo.util.IpUtils;

/**
 * 表单验证（包含验证码）过滤类
 */
@Service
public class FormAuthenticationFilter extends
		org.apache.shiro.web.filter.authc.FormAuthenticationFilter {
	@Autowired
	AccountService accountService;
	@Autowired
	FlowUserActionService flowService;

	public static final String DEFAULT_CAPTCHA_PARAM = "captcha";

	private String captchaParam = DEFAULT_CAPTCHA_PARAM;

	public String getCaptchaParam() {
		return captchaParam;
	}

	// 获取表单中用户输入的验证码
	protected String getCaptcha(ServletRequest request) {
		return WebUtils.getCleanParam(request, getCaptchaParam());
	}

	protected AuthenticationToken createToken(ServletRequest request,
			ServletResponse response) {
		String loginName = WebUtils.getCleanParam(request, "loginName");
		String loginPassword = WebUtils.getCleanParam(request, "loginPassword");
		if (loginPassword == null) {
			loginPassword = "";
		}
		boolean rememberMe = isRememberMe(request);
		String host = getHost(request);
		String captcha = getCaptcha(request);
		return new UsernamePasswordToken(loginName,
				loginPassword.toCharArray(), rememberMe, host, captcha);
	}

	@Override
	protected boolean onLoginSuccess(AuthenticationToken token,
			Subject subject, ServletRequest request, ServletResponse response)
			throws Exception {
		super.onLoginSuccess(token, subject, request, response);
		// 登录成功后续操作
		HttpServletRequest req = (HttpServletRequest) request;
		UserContext userContext = (UserContext) subject.getPrincipal();
		Users user = userContext.getUser();
		user.setLastLoginIp(user.getCurLoginIp());
		user.setLastLoginIpDisplay(user.getCurLoginIpDisplay());
		user.setCurLoginIp(IpUtils.getIpAddr(req).toString());
		user.setCurLoginIpDisplay(IpUtils.getLocationStr(user.getCurLoginIp()));
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				Constant.DATE_FORMAT_LONG_ONE);
		try {
			user.setLastLoginTime(user.getCurLoginTime());
			user.setCurLoginTime(simpleDateFormat.parse(DateUtils
					.getCurrentDate()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		user.setLoginCount(user.getLoginCount() == null ? 1 : user
				.getLoginCount() + 1);
		accountService.updateUserLoginInfo(user);
		userContext.setUser(user);

		// 记录日志

		FlowUserAction flow = new FlowUserAction();
		flow.setAddTime(simpleDateFormat.parse(DateUtils.getCurrentDate()));
		flow.setUserId(user.getId());
		flow.setIp(IpUtils.getIpAddr(req));
		flow.setType(1);// "1":登录，"2":添加用户，"3":修改密码，"4":添加数据，“5”：删除数据，"6":修改数据
		flow.setRemark("登录");
		flowService.insert_flow_user_action(flow);

		return false;
	}

	@Override
	protected boolean onLoginFailure(AuthenticationToken token,
			AuthenticationException e, ServletRequest request,
			ServletResponse response) {
		super.onLoginFailure(token, e, request, response);
		return true;
	}

}
